package jsyf.oa.service.wreport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jsyf.com.constant.Const;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.CalculateUtils;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.RegionDao;
import jsyf.oa.dao.system.SignInDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wreport.WReportCusVisitDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.entity.wreport.WReportCusVisitEntity;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import jsyf.oa.facade.system.UserFacade;
import jsyf.oa.facade.wreport.WReportCusVisitFacade;
import jsyf.oa.ientity.IBaseEntity;

/**
 * Created by Administrator on 2017/12/27 0027.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
@SuppressWarnings("all")
public class WReportCusVisitService implements WReportCusVisitFacade {
    @Autowired
    private SignInDao signInDao;
    @Autowired
    private UserFacade userFacade;

    @Autowired
    private WReportCusVisitDao wReportCusVisitDao;

    @Autowired
    private WReportCustomerDao wReportCustomerDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RegionDao regionDao;


    public WReportCusVisitEntity getEntity(String strJSON) {
        WReportCusVisitEntity entity = JSON.toJavaObject(JSON.parseObject(strJSON), WReportCusVisitEntity.class);
        return entity;
    }

    @Override
    public String save(String jsonData) {
        WReportCusVisitEntity customerVisitEntity = getEntity(jsonData);
        //customerVisitEntity.setTel(customerVisitEntity.getTel().replace(" ", ""));
        WReportCustomerEntity wReportCustomerEntity = wReportCustomerDao.getByTel(customerVisitEntity.getTel());
        if (customerVisitEntity.getVisitMode().equals("0")) {
            if (wReportCustomerEntity == null) {
                wReportCustomerEntity = new WReportCustomerEntity();
                wReportCustomerEntity.setTel(customerVisitEntity.getTel());
                wReportCustomerEntity.setName(customerVisitEntity.getName());
                wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                wReportCustomerEntity.setSource("销售录入");
                wReportCustomerDao.add(wReportCustomerEntity);
            } else {

                if (StringUtils.isBlank(wReportCustomerEntity.getCreateUserId())) {
                    wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                    wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                } else {
                    //判断该用户有没有离职
                    JSONObject userJson = userDao.getViewJSONById(wReportCustomerEntity.getCreateUserId());
                    String jobState = userJson.getString("jobState");
                    if (!jobState.equals("1")) {
                        wReportCustomerEntity.setName(wReportCustomerEntity.getName());
                        wReportCustomerEntity.setCreateUserId(wReportCustomerEntity.getCreateUserId());
                        wReportCustomerEntity.setCreateTime(wReportCustomerEntity.getCreateTime());
                    } else {
                        wReportCustomerEntity.setName(customerVisitEntity.getName());
                        wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                        wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                    }
                }
                wReportCustomerDao.update(wReportCustomerEntity);
            }
            //录入拜访记录
            JSONObject userJson = userDao.getViewJSONById(customerVisitEntity.getCreateUserId());
            WReportCusVisitEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), WReportCusVisitEntity.class);
            model.setCustomerId(wReportCustomerEntity.getId());
            String reportDate = DateUtils.getBeforeDate(new Date(), 0);
            boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
            if (isToday) {
                reportDate = DateUtils.getYesterday();
            }
            model.setReportDate(reportDate);
            model.setCreateUserId(customerVisitEntity.getCreateUserId());
            model.setVisitMode(customerVisitEntity.getVisitMode());
            if (userJson != null) {
                model.setCompanyId(userJson.get("companyId").toString());
                String roleName = userJson.get("roleName").toString();
                if (roleName.equals("区域经理")) {
                    //获取区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        model.setRegionId(regionJson.get("id").toString());
                    }
                }
                if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
                    //获取大区id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        model.setBigRegionId(regionJson.get("id").toString());
                    }
                }
            }
            //签到时间(app离线保存使用)
            JSONObject obj = JSON.parseObject(jsonData);
            if (obj.getString("arrivalsTime") != null && !"".equals(obj.getString("arrivalsTime"))) {
                Timestamp timestamp = obj.getTimestamp("arrivalsTime");
                model.setArrivalsTime(timestamp);
            } else {
                model.setArrivalsTime(wReportCusVisitDao.getCurrentTime());
            }
            wReportCusVisitDao.add(model);
            return model.getId();
        } else {
            if (wReportCustomerEntity == null) {
                //录入客户基本信息
                wReportCustomerEntity = new WReportCustomerEntity();
                wReportCustomerEntity.setName(customerVisitEntity.getName());
                wReportCustomerEntity.setTel(customerVisitEntity.getTel());
                wReportCustomerEntity.setWechat(customerVisitEntity.getWechat());
                wReportCustomerEntity.setProvinceName(customerVisitEntity.getProvinceName());
                wReportCustomerEntity.setCityName(customerVisitEntity.getCityName());
                wReportCustomerEntity.setCountyName(customerVisitEntity.getCountyName());
                wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                wReportCustomerEntity.setSource("销售录入");
                wReportCustomerDao.add(wReportCustomerEntity);
            } else {
                if (StringUtils.isBlank(wReportCustomerEntity.getCreateUserId())) {
                    wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                    wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                } else {
                    //判断该用户有没有离职
                    JSONObject userJson = userDao.getViewJSONById(wReportCustomerEntity.getCreateUserId());
                    String jobState = userJson.getString("jobState");
                    if (!jobState.equals("1")) {
                        wReportCustomerEntity.setName(wReportCustomerEntity.getName());
                        wReportCustomerEntity.setWechat(wReportCustomerEntity.getWechat());
                        wReportCustomerEntity.setCreateUserId(wReportCustomerEntity.getCreateUserId());
                        wReportCustomerEntity.setCreateTime(wReportCustomerEntity.getCreateTime());
                    } else {
                        wReportCustomerEntity.setName(customerVisitEntity.getName());
                        wReportCustomerEntity.setWechat(customerVisitEntity.getWechat());
                        wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                        wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                    }
                }


                wReportCustomerDao.update(wReportCustomerEntity);
            }
            //录入拜访记录
            JSONObject userJson = userDao.getViewJSONById(customerVisitEntity.getCreateUserId());
            JSONObject entourageJson = userDao.getViewJSONById(customerVisitEntity.getEntourageId());
            WReportCusVisitEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), WReportCusVisitEntity.class);
            model.setCustomerId(wReportCustomerEntity.getId());
            String reportDate = DateUtils.getBeforeDate(new Date(), 0);
            boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
            if (isToday) {
                reportDate = DateUtils.getYesterday();
            }
            model.setReportDate(reportDate);
            model.setCreateUserId(customerVisitEntity.getCreateUserId());
            model.setArrivalsAddress(customerVisitEntity.getArrivalsAddress());
            model.setArrivalsLatitude(customerVisitEntity.getArrivalsLatitude());
            model.setArrivalsLongitude(customerVisitEntity.getArrivalsLongitude());
            model.setVisitMode(customerVisitEntity.getVisitMode());
            model.setEntourage(customerVisitEntity.getEntourage());
            model.setEntourageId(customerVisitEntity.getEntourageId());
            if (userJson != null) {
                model.setCompanyId(userJson.get("companyId").toString());
                String roleName = userJson.get("roleName").toString();
                if (roleName.equals("区域经理")) {
                    //获取区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        model.setRegionId(regionJson.get("id").toString());
                    }
                }
                if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
                    //获取大区id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        model.setBigRegionId(regionJson.get("id").toString());
                    }
                }
            }
            if (entourageJson != null) {
                //获取陪同人员区域
                String entourageRoleName = entourageJson.get("roleName").toString();
                if (entourageRoleName.equals("区域经理")) {
                    //获取区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        model.setEntourageRegionId(regionJson.get("id").toString());
                    }
                } else if (entourageRoleName.equals("大区经理")) {
                    //获取大区id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        model.setEntourageRegionId(regionJson.get("id").toString());
                    }
                }
            }

            //签到时间(app离线保存使用)
            JSONObject obj = JSON.parseObject(jsonData);
            if (obj.getString("arrivalsTime") != null && !"".equals(obj.getString("arrivalsTime"))) {
                Timestamp timestamp = obj.getTimestamp("arrivalsTime");
                model.setArrivalsTime(timestamp);
            } else {
                model.setArrivalsTime(wReportCusVisitDao.getCurrentTime());
            }
            if (wReportCustomerEntity != null) {
                if (userJson != null) {
                    //签到录入人员姓名
                    String arrivalsName = userJson.get("name").toString();
                    //获取当天哪个销售在拜访这个客户并且没有签退
                    JSONObject visitJsonObject = wReportCusVisitDao.getCustomerVistInfo(wReportCustomerEntity.getId(), DateUtils.getBeforeDate(new Date(), 0));
                    if (visitJsonObject != null) {
                        if (customerVisitEntity.getArrivalsLongitude() != null && customerVisitEntity.getArrivalsLatitude() != null) {
                            Double visitLongitude = Double.valueOf("".equals(visitJsonObject.get("arrivalsLongitude").toString()) ? "0.00" : visitJsonObject.get("arrivalsLongitude").toString());
                            Double visitLatitude = Double.valueOf("".equals(visitJsonObject.get("arrivalsLatitude").toString()) ? "0.00" : visitJsonObject.get("arrivalsLatitude").toString());
                            Double arrivalsLongitude = Double.valueOf("".equals(customerVisitEntity.getArrivalsLongitude().toString()) ? "0.00" : customerVisitEntity.getArrivalsLongitude().toString());
                            Double arrivalsLatitude = Double.valueOf("".equals(customerVisitEntity.getArrivalsLatitude().toString()) ? "0.00" : customerVisitEntity.getArrivalsLatitude().toString());
                            Double s = CalculateUtils.GetDistance(visitLatitude, visitLongitude, arrivalsLatitude, arrivalsLongitude);
                            if (s <= 500) {
                                //签到录入在500米范围之内,自动匹配双方陪同人员
                                WReportCusVisitEntity visitEntity = (WReportCusVisitEntity) wReportCusVisitDao.getIBaseEntityById(visitJsonObject.get("id").toString());
                                visitEntity.setSysEntourage(arrivalsName);
                                visitEntity.setSysEntourageId(customerVisitEntity.getCreateUserId());
                                wReportCusVisitDao.update(visitEntity);
                                model.setSysEntourageId(visitJsonObject.get("createUserId").toString());
                                model.setSysEntourage(visitJsonObject.get("salerName").toString());
                            }
                        }
                    }
                }
            }
            wReportCusVisitDao.add(model);


            return model.getId();
        }
    }

    @Override
    public Integer update(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //leaveTime
        String leaveTime = jsonParams.getString("leaveTime");

        WReportCusVisitEntity customerVisitEntity = getEntity(jsonData);
        WReportCustomerEntity wReportCustomerEntity = wReportCustomerDao.getByTel(customerVisitEntity.getTel());

        if (StringUtils.isBlank(wReportCustomerEntity.getCreateUserId())) {
            wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
            wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
        } else {
            //判断该用户有没有离职
            JSONObject userJson = userDao.getViewJSONById(wReportCustomerEntity.getCreateUserId());
            String jobState = userJson.getString("jobState");
            if (!jobState.equals("1")) {
                wReportCustomerEntity.setName(wReportCustomerEntity.getName());
                wReportCustomerEntity.setWechat(wReportCustomerEntity.getWechat());
                wReportCustomerEntity.setCreateUserId(wReportCustomerEntity.getCreateUserId());
                wReportCustomerEntity.setCreateTime(wReportCustomerEntity.getCreateTime());
            } else {
                wReportCustomerEntity.setName(customerVisitEntity.getName());
                wReportCustomerEntity.setWechat(customerVisitEntity.getWechat());
                wReportCustomerEntity.setCreateUserId(customerVisitEntity.getCreateUserId());
                wReportCustomerEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
            }
        }

        wReportCustomerEntity.setName(customerVisitEntity.getName());
        wReportCustomerEntity.setWechat(customerVisitEntity.getWechat());
        wReportCustomerEntity.setProvinceName(customerVisitEntity.getProvinceName());
        wReportCustomerEntity.setCityName(customerVisitEntity.getCityName());
        wReportCustomerEntity.setCountyName(customerVisitEntity.getCountyName());
        wReportCustomerDao.update(wReportCustomerEntity);


        WReportCusVisitEntity wReportCusVisitEntity = (WReportCusVisitEntity) wReportCusVisitDao.getIBaseEntityById(customerVisitEntity.getId());
        wReportCusVisitEntity.setProvinceName(customerVisitEntity.getProvinceName());
        wReportCusVisitEntity.setCityName(customerVisitEntity.getCityName());
        wReportCusVisitEntity.setCountyName(customerVisitEntity.getCountyName());
        wReportCusVisitEntity.setLeaveLongitude(customerVisitEntity.getLeaveLongitude());
        wReportCusVisitEntity.setLeaveImg(customerVisitEntity.getLeaveImg());
        wReportCusVisitEntity.setLeaveLatitude(customerVisitEntity.getLeaveLatitude());
        wReportCusVisitEntity.setLeaveAddress(customerVisitEntity.getLeaveAddress());
        wReportCusVisitEntity.setFundCondition(customerVisitEntity.getFundCondition());
        wReportCusVisitEntity.setExistingDevice(customerVisitEntity.getExistingDevice());
        wReportCusVisitEntity.setOtherCondition(customerVisitEntity.getOtherCondition());
        if (leaveTime != null && !(leaveTime.equals("")) & leaveTime != " ") {
            wReportCusVisitEntity.setLeaveTime(wReportCusVisitDao.getCurrentTime());
        }

        return wReportCusVisitDao.update(wReportCusVisitEntity);
    }

    @Override
    public JSONObject getCustomerVisitById(String id) {
        return wReportCusVisitDao.getViewJSONById(id);
    }


    @Override
    public JSONObject getLatestCustomerVisitByTel(String userId, String visitMode, String tel) {
        return wReportCusVisitDao.getLatestCustomerVisitByTel(userId, visitMode, tel);
    }


    @Override
    public List<JSONObject> getCustomerListById(String userId, String reportDate, String visitMode) {
        boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
        if (isToday) {
            reportDate = DateUtils.getYesterday();
        }
        JSONObject front = userDao.getViewJSONById(userId);
        Integer frontFlag = null;
        if (front != null) {
            frontFlag = front.getInteger("frontFlag");
        }
        if ("区域经理".equals(front.getString("roleName")) || frontFlag != 1) {
            return wReportCusVisitDao.getViewJSONListByCondition("AND createUserId=?  AND reportDate=? AND visitMode=?  ORDER BY salerName ASC,arrivalsTime desc ", new Object[]{userId, reportDate, visitMode});
        } else {
            List<String> listUserIds = new ArrayList<>();
            listUserIds.add(userId);
            userDao.getChildrenIds(userId, listUserIds);
            String userIds = "";
            for (int i = 0; i < listUserIds.size(); i++) {
                userIds += "'" + listUserIds.get(i) + "',";
            }
            if (userIds.length() > 0) {
                userIds = userIds.substring(0, userIds.length() - 1);
            }
            List<JSONObject> parentList = wReportCusVisitDao.getViewJSONListByCondition("AND (createUserId IN (" + userIds + ") OR entourageId='" + userId + "') AND reportDate=? AND visitMode=?  ORDER BY  salerName ASC,arrivalsTime desc ", new Object[]{reportDate, visitMode});
            return parentList;
        }
    }

    @Override
    public String faceInApp(String jsonData) {
        //查询当天是否有未签退的记录, 有面访未签退的不能连续保存
        WReportCusVisitEntity model = getEntity(jsonData);
        //model.setTel(model.getTel().replace(" ", ""));
        List<IBaseEntity> list = wReportCusVisitDao.getIBaseEntityByCondition(" AND CREATE_USER_ID = ? and REPORT_DATE = ? and VISIT_MODE='1' ", new Object[]{model.getCreateUserId(), DateUtils.getBeforeDate(new Date(), 0)});
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                WReportCusVisitEntity visit = (WReportCusVisitEntity) list.get(i);
                if (visit.getLeaveImg() == null || "".equals(visit.getLeaveImg())) {
                    return "还有未签退的记录";
                }
            }
        }

        if (model != null && model.getTel() != null && !model.getTel().isEmpty()) {
            //签到录入电话
            String id = save(jsonData);
            //保存首次拜访与签到差距
            JSONObject obj = new JSONObject();
            obj.put("userId", model.getCreateUserId());
            obj.put("signDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            obj.put("signOutAddress", "");
            signInDao.saveFirstOrLastVisitDiff(JSON.toJSONString(obj));
            return id;
        } else {
            //签到没录入电话,直接插入一条跟踪
            JSONObject userJson = userDao.getViewJSONById(model.getCreateUserId());
            JSONObject entourageJson = userDao.getViewJSONById(model.getEntourageId());
            model.setCustomerId(null);
            String reportDate = DateUtils.getBeforeDate(new Date(), 0);
            boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
            if (isToday) {
                reportDate = DateUtils.getYesterday();
            }
            model.setReportDate(reportDate);
            if (userJson != null) {
                model.setCompanyId(userJson.get("companyId").toString());
                String roleName = userJson.get("roleName").toString();
                if (roleName.equals("区域经理")) {
                    //获取区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        model.setRegionId(regionJson.get("id").toString());
                    }
                }
                if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
                    //获取大区id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        model.setBigRegionId(regionJson.get("id").toString());
                    }
                }
            }
            if (entourageJson != null) {
                //获取陪同人员区域
                String entourageRoleName = entourageJson.get("roleName").toString();
                if (entourageRoleName.equals("区域经理")) {
                    //获取区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        model.setEntourageRegionId(regionJson.get("id").toString());
                    }
                } else if (entourageRoleName.equals("大区经理")) {
                    //获取大区id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        model.setEntourageRegionId(regionJson.get("id").toString());
                    }
                }
            }
            //签到时间(app离线保存使用)
            JSONObject obj = JSON.parseObject(jsonData);
            if (obj.getString("arrivalsTime") != null && !"".equals(obj.getString("arrivalsTime"))) {
                Timestamp timestamp = obj.getTimestamp("arrivalsTime");
                model.setArrivalsTime(timestamp);
            } else {
                model.setArrivalsTime(wReportCusVisitDao.getCurrentTime());
            }
            wReportCusVisitDao.add(model);
            //保存首次拜访与签到差距
            JSONObject obj2 = new JSONObject();
            obj2.put("userId", model.getCreateUserId());
            obj2.put("signDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            obj2.put("signOutAddress", "");
            obj2.put("longitude",model.getArrivalsLongitude());
            obj2.put("latitude",model.getArrivalsLatitude());
            signInDao.saveFirstOrLastVisitDiff(JSON.toJSONString(obj2));
            return model.getId();
        }
    }

    @Override
    public String faceOutApp(String jsonData) {
        WReportCusVisitEntity visitEntity = getEntity(jsonData);

        WReportCusVisitEntity wReportCusVisitEntity = (WReportCusVisitEntity) wReportCusVisitDao.getIBaseEntityById(visitEntity.getId());
        //wReportCusVisitEntity.setTel(wReportCusVisitEntity.getTel().replace(" ", ""));
        if (visitEntity != null && visitEntity.getTel() != null && !visitEntity.getTel().isEmpty()) {
            //签退先查询电话是否是老客户
            WReportCustomerEntity oldCusEntity = wReportCustomerDao.getByTel(visitEntity.getTel());
            if (oldCusEntity != null) {
                //如果是老客户,以新录入信息为准
                if (StringUtils.isBlank(oldCusEntity.getCreateUserId())) {
                    oldCusEntity.setCreateUserId(visitEntity.getCreateUserId());
                    oldCusEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                } else {
                    //判断该用户有没有离职
                    JSONObject userJson = userDao.getViewJSONById(oldCusEntity.getCreateUserId());
                    String jobState = userJson.getString("jobState");
                    if (!jobState.equals("1")) {
                        oldCusEntity.setCreateUserId(oldCusEntity.getCreateUserId());
                        oldCusEntity.setCreateTime(oldCusEntity.getCreateTime());
                    } else {
                        oldCusEntity.setCreateUserId(visitEntity.getCreateUserId());
                        oldCusEntity.setCreateTime(wReportCusVisitDao.getCurrentTime());
                    }
                }
                oldCusEntity.setProvinceName(visitEntity.getProvinceName());
                oldCusEntity.setCityName(visitEntity.getCityName());
                oldCusEntity.setCountyName(visitEntity.getCountyName());

                oldCusEntity.setCompanyName(visitEntity.getCompanyName());
                oldCusEntity.setName(visitEntity.getName());
                oldCusEntity.setWechat(visitEntity.getWechat());
                oldCusEntity.setCustomerType(visitEntity.getCustomerType());
                oldCusEntity.setCustomerCredit(visitEntity.getCustomerCredit());
                oldCusEntity.setOtherCondition(visitEntity.getOtherCondition());
                oldCusEntity.setServerCondition(visitEntity.getServerCondition());

                oldCusEntity.setOtherVisitType(visitEntity.getOtherVisitType());
                oldCusEntity.setAccessoriesChargesCondition(visitEntity.getAccessoriesChargesCondition());
                oldCusEntity.setHoursChargesCondition(visitEntity.getHoursChargesCondition());
                oldCusEntity.setSerialNo(visitEntity.getSerialNo());

                oldCusEntity.setDebtCondition(visitEntity.getDebtCondition());
                oldCusEntity.setLettersCondition(visitEntity.getLettersCondition());
                oldCusEntity.setServerCustomerType(visitEntity.getServerCustomerType());
                oldCusEntity.setIntentionModel(visitEntity.getIntentionModel());

                oldCusEntity.setDeviceInfo(visitEntity.getDeviceInfo());
                oldCusEntity.setDeviceHour(visitEntity.getDeviceHour());
                oldCusEntity.setMachineNo(visitEntity.getMachineNo());
                wReportCustomerDao.update(oldCusEntity);
                wReportCusVisitEntity.setCustomerId(oldCusEntity.getId());
            } else {
                //新客户,插入客户
                WReportCustomerEntity newCusEntity = new WReportCustomerEntity();
                newCusEntity.setProvinceName(visitEntity.getProvinceName());
                newCusEntity.setCityName(visitEntity.getCityName());
                newCusEntity.setCountyName(visitEntity.getCountyName());

                newCusEntity.setCompanyName(visitEntity.getCompanyName());
                newCusEntity.setName(visitEntity.getName());
                newCusEntity.setTel(visitEntity.getTel());
                newCusEntity.setWechat(visitEntity.getWechat());
                newCusEntity.setCustomerType(visitEntity.getCustomerType());
                newCusEntity.setCustomerCredit(visitEntity.getCustomerCredit());
                newCusEntity.setServerCondition(visitEntity.getServerCondition());
                newCusEntity.setWechat(visitEntity.getWechat());
                newCusEntity.setCreateUserId(visitEntity.getCreateUserId());
                newCusEntity.setSource("销售录入");
                newCusEntity.setOtherCondition(visitEntity.getOtherCondition());
                newCusEntity.setOtherVisitType(visitEntity.getOtherVisitType());
                newCusEntity.setAccessoriesChargesCondition(visitEntity.getAccessoriesChargesCondition());
                newCusEntity.setHoursChargesCondition(visitEntity.getHoursChargesCondition());
                newCusEntity.setSerialNo(visitEntity.getSerialNo());


                newCusEntity.setDebtCondition(visitEntity.getDebtCondition());
                newCusEntity.setLettersCondition(visitEntity.getLettersCondition());
                newCusEntity.setServerCustomerType(visitEntity.getServerCustomerType());
                newCusEntity.setIntentionModel(visitEntity.getIntentionModel());

                newCusEntity.setDeviceInfo(visitEntity.getDeviceInfo());
                newCusEntity.setDeviceHour(visitEntity.getDeviceHour());
                newCusEntity.setMachineNo(visitEntity.getMachineNo());

                wReportCustomerDao.add(newCusEntity);

                wReportCusVisitEntity.setCustomerId(newCusEntity.getId());
            }

            //在更新拜访记录
            if (visitEntity.getEntourageId() == null || visitEntity.getEntourageId().isEmpty()) {
                wReportCusVisitEntity.setEntourage("无");
            }
            wReportCusVisitEntity.setProvinceName(visitEntity.getProvinceName());
            wReportCusVisitEntity.setCityName(visitEntity.getCityName());
            wReportCusVisitEntity.setCountyName(visitEntity.getCountyName());

            wReportCusVisitEntity.setCompanyName(visitEntity.getCompanyName());
            wReportCusVisitEntity.setLeaveLongitude(visitEntity.getLeaveLongitude());
            wReportCusVisitEntity.setEntourage(visitEntity.getEntourage());
            wReportCusVisitEntity.setEntourageId(visitEntity.getEntourageId());
            wReportCusVisitEntity.setCustomerType(visitEntity.getCustomerType());
            wReportCusVisitEntity.setCustomerCredit(visitEntity.getCustomerCredit());
            wReportCusVisitEntity.setLeaveImg(visitEntity.getLeaveImg());
            wReportCusVisitEntity.setLeaveLatitude(visitEntity.getLeaveLatitude());
            wReportCusVisitEntity.setLeaveAddress(visitEntity.getLeaveAddress());
            wReportCusVisitEntity.setFundCondition(visitEntity.getFundCondition());
            wReportCusVisitEntity.setServerCondition(visitEntity.getServerCondition());
            wReportCusVisitEntity.setTrackType(visitEntity.getTrackType());
            wReportCusVisitEntity.setExistingDevice(visitEntity.getExistingDevice());
            wReportCusVisitEntity.setOtherCondition(visitEntity.getOtherCondition());

            wReportCusVisitEntity.setOtherVisitType(visitEntity.getOtherVisitType());
            wReportCusVisitEntity.setAccessoriesChargesCondition(visitEntity.getAccessoriesChargesCondition());
            wReportCusVisitEntity.setHoursChargesCondition(visitEntity.getHoursChargesCondition());
            wReportCusVisitEntity.setSerialNo(visitEntity.getSerialNo());

            wReportCusVisitEntity.setDebtCondition(visitEntity.getDebtCondition());
            wReportCusVisitEntity.setLettersCondition(visitEntity.getLettersCondition());
            wReportCusVisitEntity.setServerCustomerType(visitEntity.getServerCustomerType());
            wReportCusVisitEntity.setIntentionModel(visitEntity.getIntentionModel());

            wReportCusVisitEntity.setDeviceInfo(visitEntity.getDeviceInfo());
            wReportCusVisitEntity.setDeviceHour(visitEntity.getDeviceHour());
            wReportCusVisitEntity.setMachineNo(visitEntity.getMachineNo());
            wReportCusVisitEntity.setFeeDesc(visitEntity.getFeeDesc());
            wReportCusVisitEntity.setFeeType(visitEntity.getFeeType());

            //签退时间
            JSONObject obj = JSON.parseObject(jsonData);
            if (obj.getString("leaveTime") != null && !"".equals(obj.getString("leaveTime"))) {
                Timestamp timestamp = obj.getTimestamp("leaveTime");
                wReportCusVisitEntity.setLeaveTime(timestamp);
            } else {
                wReportCusVisitEntity.setLeaveTime(wReportCusVisitDao.getCurrentTime());
                //插入时间间隔: 签退时间 - 签到时间
                long diff = wReportCusVisitEntity.getLeaveTime().getTime() - wReportCusVisitEntity.getArrivalsTime().getTime();
                String str = String.valueOf(diff);
                double dif = Double.parseDouble(str);
                double visitTime = Math.abs(Math.ceil(dif / (1000 * 60.0)));
                wReportCusVisitEntity.setVisitTime(((int) visitTime) + "");
            }
            wReportCusVisitDao.update(wReportCusVisitEntity);
            //保存末次拜访与考勤签退差距
            JSONObject obj3 = new JSONObject();
            obj3.put("userId", wReportCusVisitEntity.getCreateUserId());
            obj3.put("signDate", wReportCusVisitEntity.getReportDate());
            obj3.put("signOutAddress", "1");
            signInDao.saveFirstOrLastVisitDiff(JSON.toJSONString(obj3));

            //如果陪跑拜访, 需要保存陪跑两者人员之间的签到距离, 同时更新两个人的distance字段
            JSONObject entourageObj = wReportCusVisitDao.getEntourageDistance(wReportCusVisitEntity.getCustomerId(), wReportCusVisitEntity.getCreateUserId(), wReportCusVisitEntity.getReportDate());
            if (entourageObj != null) {
                WReportCusVisitEntity entourageVisitEntity = (WReportCusVisitEntity) wReportCusVisitDao.getIBaseEntityById(entourageObj.getString("entourageVisitId"));
                entourageVisitEntity.setEntourageDistance(entourageObj.getString("distance"));
                wReportCusVisitEntity.setEntourageDistance(entourageObj.getString("distance"));
                wReportCusVisitDao.update(entourageVisitEntity);
                wReportCusVisitDao.update(wReportCusVisitEntity);
            }


        }
        return wReportCusVisitEntity.getId();
    }

    @Override
    public String removeApp(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        int flag = wReportCusVisitDao.removeById(id);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public List<JSONObject> accompaniedVisitCus(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String reportDate = jsonParams.getString("reportDate");
        boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
        if (isToday) {
            reportDate = DateUtils.getYesterday();
        }
        JSONObject jsonObject = userDao.getViewJSONById(userId);
        Integer frontFlag = null;
        Integer areaType = null;
        if (jsonObject != null) {
            frontFlag = jsonObject.getInteger("frontFlag");
            areaType = jsonObject.getInteger("areaType");
        }
        if (frontFlag == 1 && areaType == 0) {
            return wReportCusVisitDao.getViewJSONListByCondition("AND entourageId=? AND reportDate=? AND visitMode =1 AND entourageId IS not NULL ORDER BY salerName ASC,arrivalsTime desc ", new Object[]{userId, reportDate});
        } else {
            return wReportCusVisitDao.getViewJSONListByCondition("AND createUserId =? AND reportDate=? AND visitMode =1  AND entourageId is not NULL ORDER BY  salerName ASC,arrivalsTime desc ", new Object[]{userId, reportDate});
        }
    }

    @Override
    public List<JSONObject> selfVisitCus(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String reportDate = jsonParams.getString("reportDate");
        boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
        if (isToday) {
            reportDate = DateUtils.getYesterday();
        }
        JSONObject jsonObject = userDao.getViewJSONById(userId);
        Integer frontFlag = null;
        Integer areaType = null;
        if (jsonObject != null) {
            frontFlag = jsonObject.getInteger("frontFlag");
            areaType = jsonObject.getInteger("areaType");
        }
        if (frontFlag == 1 && areaType == 0) {
            return wReportCusVisitDao.getViewJSONListByCondition("AND entourageId =? AND reportDate=? AND visitMode =1 ORDER BY  salerName ASC,arrivalsTime desc ", new Object[]{userId, reportDate});
        } else {
            return wReportCusVisitDao.getViewJSONListByCondition("AND createUserId=? AND reportDate=? AND visitMode =1 AND entourageId IS NULL ORDER BY salerName ASC,arrivalsTime desc ", new Object[]{userId, reportDate});
        }
    }

    @Override
    public String accompaniedVisitCusOutApp(String jsonData) {
        WReportCusVisitEntity model = getEntity(jsonData);

        JSONObject userJson = userDao.getViewJSONById(model.getCreateUserId());
        JSONObject entourageJson = userDao.getViewJSONById(model.getEntourageId());
        if (model.getEntourageId() == null || model.getEntourageId().isEmpty()) {
            model.setEntourage("无");
        } else {
            model.setEntourage(entourageJson.getString("name"));
        }
        String reportDate = DateUtils.getBeforeDate(new Date(), 0);
        boolean isToday = DateUtils.isInDate(new Date(), "00:00:00", "03:00:00");
        if (isToday) {
            reportDate = DateUtils.getYesterday();
        }
        model.setReportDate(reportDate);
        if (userJson != null) {
            model.setCompanyId(userJson.get("companyId").toString());
            String roleName = userJson.get("roleName").toString();
            if (roleName.equals("区域经理")) {
                //获取区域id
                JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID != '0'");
                if (regionJson != null) {
                    model.setRegionId(regionJson.get("id").toString());
                }
            }
            if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
                //获取大区id
                JSONObject regionJson = regionDao.getRegionByRoleName(model.getCreateUserId(), " AND PARENT_ID = '0'");
                if (regionJson != null) {
                    model.setBigRegionId(regionJson.get("id").toString());
                }
            }
        }
        if (entourageJson != null) {
            //获取陪同人员区域
            String entourageRoleName = entourageJson.get("roleName").toString();
            if (entourageRoleName.equals("区域经理")) {
                //获取区域id
                JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID != '0'");
                if (regionJson != null) {
                    model.setEntourageRegionId(regionJson.get("id").toString());
                }
            } else if (entourageRoleName.equals("大区经理")) {
                //获取大区id
                JSONObject regionJson = regionDao.getRegionByRoleName(model.getEntourageId(), " AND PARENT_ID = '0'");
                if (regionJson != null) {
                    model.setEntourageRegionId(regionJson.get("id").toString());
                }
            }
        }
        model.setArrivalsTime(wReportCusVisitDao.getCurrentTime());
        model.setVisitMode("1");
        wReportCusVisitDao.add(model);
        return model.getId();

        //return null;
    }
//
//    @Override
//    public Integer update(String jsonData) {
//        return null;
//    }
//
//    @Override
//    public List<JSONObject> getSignListByUserId(String userId) {
//        return null;
//    }
}
